import { eventTrack, messages } from "share/common";
import React, { Component } from "react";
import { Popover, Spin } from "antd";
import menuRoute from "routes/menuRoute";
import "styles/dashboard/quick-tool.scss";
import Stations from "components/template/proxies/stations";
import leftImg from "images/dashboard/refactor/left.png";
import rightImg from "images/dashboard/refactor/right.png";
import SVGIcon from "components/SVGIcon";
import proxiesService from "components/template/proxies/proxies-service";
import publicImg from "images/dashboard/refactor/public.png";
import loanImg from "images/dashboard/refactor/loan.png";
import applicationImg from "images/dashboard/refactor/application.png";
import reimbursementImg from "images/dashboard/refactor/reimbursement.png";
import noHistoryImg from "images/dashboard/refactor/no-history.png";

class QuickTool extends Component {
  constructor(props) {
    super(props);
    this.state = {
      childVisible: false,
      popOverShowMap: {},
      visible: false,
      currentType: "101",
      currentKey: "application",
      listLoading: false,
      historyLoading: false,
      forms: [],
      history: [],
      documentOpenMap: {
        1001: !!props.menuTree.keyUrl.request,
        1002: !!props.menuTree.keyUrl["expense-report"],
        3001: !!props.menuTree.keyUrl["my-borrow"],
        3004: !!props.menuTree.keyUrl["corporate-payment-report"],
      },
    };
    this.formStationsCodeMap = {
      application: "101",
      reimbursement: "102",
      loan: "104",
      public: "106",
    };
    this.formCodeMap = {
      application: ["2001", "2002", "2004"],
      reimbursement: ["3001", "3002", "3003"],
      loan: ["2005", "2006"],
      public: ["3004"],
    };
    this.formImgMap = {
      application: { src: applicationImg, name: messages("basic-1.key18") /*申请单*/, entityType: "1001" },
      reimbursement: { src: reimbursementImg, name: messages("basic-1.key19") /*报销单*/, entityType: "1002" },
      loan: { src: loanImg, name: messages("basic-1.key20") /*借款单*/, entityType: "3001" },
      public: { src: publicImg, name: messages("basic-1.key208") /*对公支付单*/, entityType: "3004" },
    };
    this.formNewMap = {
      application: ({ formOID, jobId }) => {
        let url = menuRoute.getRouteItem("new-request", "key").url;
        url = url.replace(":formOID", formOID);
        url = url.replace(":jobId", jobId);
        this.context.router.push(url);
      },
      reimbursement: ({ formOID, userOID, jobId }) => {
        this.context.router.push(
          menuRoute
            .getRouteItem("new-expense-report")
            .url.replace(":formId", formOID)
            .replace(":userOID", userOID)
            .replace(":applicantJobId", jobId)
        );
      },
      loan: ({ formOID, jobId, userOID }) => {
        this.context.router.push(
          menuRoute
            .getRouteItem("new-borrow")
            .url.replace(":formOID", formOID)
            .replace(":jobId", jobId)
            .replace(":applicantOID", userOID)
        );
      },
      public: ({ formOID, jobId, userOID }) => {
        this.context.router.push(
          menuRoute
            .getRouteItem("new-corporate-payment-report")
            .url.replace(":formId", formOID)
            .replace(":userOID", userOID)
            .replace(":applicantJobId", jobId)
        );
      },
    };
  }

  componentWillMount() {}

  componentDidMount() {
    this.getAllApplication();
    this.getHistory();
  }

  componentWillUnmount() {}

  getJobId = () => {
    const { user } = this.props;
    const temp = [];
    let defaultId;
    user.companyWithUserJobsDTOList &&
      user.companyWithUserJobsDTOList.map((item) => {
        item.userJobsDTOList.map((it) => {
          if (it.docDefault === true) {
            defaultId = it.id;
          }
          temp.push(it);
        });
      });
    return temp[0].id;
  };

  getAllApplication = () => {
    const { user } = this.props;
    this.setState({ listLoading: true });
    if (user.multiJob) {
      this.setState({ listLoading: false });
    } else {
      const params = { formType: 103 };
      proxiesService
        .getProxyMyForms(params)
        .then((res) => {
          if (res.status === 200) {
            this.setState({ forms: res.data, listLoading: false });
          } else {
            this.setState({ listLoading: false });
          }
        })
        .catch(() => {
          this.setState({ listLoading: false });
        });
    }
  };

  getHistory = () => {
    this.setState({ historyLoading: true });
    proxiesService
      .getHistoryDocument()
      .then((res) => {
        if (res.status === 200) {
          this.setState({ history: res.data, historyLoading: false });
        } else {
          this.setState({ historyLoading: false });
        }
      })
      .catch(() => {
        this.setState({ historyLoading: false });
      });
  };

  handleCreate = (item) => {
    Object.keys(this.formCodeMap).find((key) => {
      if (this.formCodeMap[key].includes(`${item.formType}`)) {
        this.formNewMap[key]({ formOID: item.formOID, userOID: item.applicantOID, jobId: item.jobId });
        eventTrack({
          category: "1218-新首页-埋点",
          action: "点击了【最近使用】创建单据",
          label: this.props.tenant.tenantName,
        });
        return true;
      }
    });
  };

  handleQuickCreate = (item) => {
    const { user } = this.props;
    Object.keys(this.formCodeMap).find((key) => {
      if (this.formCodeMap[key].includes(`${item.formType}`)) {
        this.formNewMap[key]({ formOID: item.formOID, userOID: user.userOID, jobId: this.getJobId() });
        eventTrack({
          category: "1218-新首页-埋点",
          action: "通过【提单据】创建单据",
          label: this.props.tenant.tenantName,
        });
        return true;
      }
    });
  };

  handleStationsNew = (formOID, jobId, userOID) => {
    this.formNewMap[this.state.currentKey]({ formOID, userOID, jobId });
  };

  handleMultiNew = (key) => {
    this.setState({ currentType: this.formStationsCodeMap[key], visible: false, currentKey: key }, () => {
      if (this.stationsRef.state.selectedJobId) {
        this.stationsRef.handleChangeJob(this.stationsRef.state.selectedJobId);
      }
      this.stationsRef.handleMultiJob();
    });
    eventTrack({
      category: "1218-新首页-埋点",
      action: "通过【提单据】创建单据",
      label: this.props.tenant.tenantName,
    });
  };

  onVisibleChange = (e) => {
    this.setState({ visible: e }, () => {
      this.handlePopover(e);
    });
  };

  onChildVisibleChange = (e) => {
    this.setState({ childVisible: e });
  };

  handlePopover = (e) => {
    const { forms } = this.state;
    if (e) {
      const popOverShowMap = {};
      Object.keys(this.formImgMap).map((key, outIndex) => {
        const haveForms = forms.filter((form) => {
          return this.formCodeMap[key].includes(`${form.formType}`);
        });
        if (haveForms && haveForms.length > 0) {
          forms
            .filter((form) => {
              return this.formCodeMap[key].includes(`${form.formType}`);
            })
            .map((singleForm, innerIndex) => {
              popOverShowMap[`single-form-${outIndex}-${innerIndex}`] =
                document.querySelector(`.single-form-${outIndex}-${innerIndex}`) &&
                document.querySelector(`.single-form-${outIndex}-${innerIndex}`).scrollHeight >
                  document.querySelector(`.single-form-${outIndex}-${innerIndex}`).clientHeight;
            });
        }
      });
      this.setState({ popOverShowMap });
    }
  };

  goToMyAccount = () => {
    this.context.router.push({
      pathname: menuRoute.getRouteItem("my-account").url,
      state: { autoOpen: true },
    });
    eventTrack({
      category: "1218-新首页-埋点",
      action: "点击了【记费用】",
      label: this.props.tenant.tenantName,
    });
  };

  renderContent = () => {
    const { user } = this.props;
    const { forms, listLoading, documentOpenMap, popOverShowMap } = this.state;
    const anyOpen = Object.keys(documentOpenMap).find((key) => {
      return documentOpenMap[key];
    });
    if (listLoading) {
      return (
        <Spin spinning={listLoading}>
          <div className="loading-box" />
        </Spin>
      );
    } else if (user.multiJob && anyOpen) {
      return (
        <div className="quick-add-content-multi">
          {Object.keys(this.formImgMap).map((key) => {
            return (
              documentOpenMap[this.formImgMap[key].entityType] && (
                <div
                  className="quick-add-content-multi-single"
                  onClick={() => {
                    this.handleMultiNew(key);
                  }}
                >
                  <div className="img-box">
                    <img src={this.formImgMap[key].src} className="img" />
                  </div>
                  <div className="document-title">{this.formImgMap[key].name}</div>
                </div>
              )
            );
          })}
        </div>
      );
    }
    return (
      <div className="quick-add-content">
        {Object.keys(this.formImgMap).map((key, outIndex) => {
          const haveForms = forms.filter((form) => {
            return this.formCodeMap[key].includes(`${form.formType}`);
          });
          if (haveForms && haveForms.length > 0) {
            return (
              <div className="single-document">
                <div className="img-title-box">
                  <div className="img-box">
                    <img src={this.formImgMap[key].src} className="img" />
                  </div>
                  <div className="document-title">{this.formImgMap[key].name}</div>
                </div>
                <div className="form-list-box">
                  {forms
                    .filter((form) => {
                      return this.formCodeMap[key].includes(`${form.formType}`);
                    })
                    .map((singleForm, innerIndex) => {
                      return (
                        <Popover
                          onVisibleChange={this.onChildVisibleChange}
                          trigger={popOverShowMap[`single-form-${outIndex}-${innerIndex}`] ? "hover" : ""}
                          content={singleForm.formName}
                        >
                          <div
                            onClick={() => {
                              this.handleQuickCreate(singleForm);
                            }}
                            className={`single-form single-form-${outIndex}-${innerIndex}`}
                          >
                            {singleForm.formName}
                          </div>
                        </Popover>
                      );
                    })}
                </div>
              </div>
            );
          }
          return <span />;
        })}
        {forms && forms.length === 0 && (
          <div className="empty-content">
            <div className="img-box">
              <img src={noHistoryImg} className="img" />
            </div>
            <div className="tip">{messages("basic-1.key209") /*无可创建单据，请联系管理员*/}</div>
          </div>
        )}
      </div>
    );
  };

  render() {
    const { uniKey, enableDrag } = this.props;
    const { history, historyLoading, currentType, visible, childVisible } = this.state;
    return (
      <div id={`home-${uniKey}`} data-id={`home-${uniKey}`} className="two-third-width home-quick-tool">
        <div className="main-box" id="quick-tool-mask-guide-id">
          <div className="quick-add">
            <div className="home-title">{messages("basic-1.key205") /*快速新建*/}</div>
            <div className="quick-btn">
              <div className="left-btn" onClick={this.goToMyAccount}>
                <div className="img-box">
                  <img className="img" src={leftImg} />
                </div>
                <div className="bubble" />
                <div className="title">{messages("basic-1.key210") /*记费用*/}</div>
              </div>
              <Popover
                getPopupContainer={() => {
                  return document.querySelector(".dashboard-refactor");
                }}
                trigger={childVisible ? "click" : "hover"}
                visible={visible}
                onVisibleChange={this.onVisibleChange}
                autoAdjustOverflow
                overlayClassName="quick-add-popover"
                placement="bottom"
                content={this.renderContent()}
              >
                <div className="right-btn">
                  <div className="img-box">
                    <img className="img" src={rightImg} />
                  </div>
                  <div className="bubble" />
                  <div className="title"> {messages("basic-1.key211") /*提单据*/}</div>
                  <SVGIcon className="down-triangle" type="home-down-triangle" />
                </div>
              </Popover>
            </div>
          </div>
          <div className="recent">
            <Spin spinning={historyLoading}>
              <div className="recent-box">
                <div className="recent-title">{messages("basic-1.key212") /*最近使用*/}</div>
                <div className="quick-form-list">
                  {history.map((item) => {
                    const node = (
                      <div className="item">
                        <div className="form-name">{item.formName}</div>
                        <div className="position">{item.userInfo}</div>
                      </div>
                    );
                    return (
                      <Popover
                        getPopupContainer={() => {
                          return document.querySelector(".dashboard-refactor");
                        }}
                        onClick={() => {
                          this.handleCreate(item);
                        }}
                        placement="topLeft"
                        content={node}
                      >
                        {node}
                      </Popover>
                    );
                  })}
                  {history && history.length === 0 && (
                    <div className="empty-content">
                      <div className="img-box">
                        <img src={noHistoryImg} className="img" />
                      </div>
                      <div className="tip">{messages("basic-1.key213") /*未创建单据*/}</div>
                    </div>
                  )}
                </div>
              </div>
            </Spin>
          </div>
          <div className="invisible-stations">
            <Stations onRef={(ref) => (this.stationsRef = ref)} formType={currentType} onOk={this.handleStationsNew} />
          </div>
        </div>
        {enableDrag && <div className="toggle-drag-box" />}
      </div>
    );
  }
}

QuickTool.contextTypes = {
  router: React.PropTypes.object,
};

export default QuickTool;
